package com.hdy.javachatroomdemo.Model;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class OnlineUserMapper {
    //由于此处的映射表是在多线程的环境下进行的所以改成concurrentHashMap
    private final Map<Integer, WebSocketSession> map = new ConcurrentHashMap<>();

    //1.添加映射关系
    public void add(User user, WebSocketSession session) {
        //这里要防止多开的情况 map.get(user.getId())==session也可以作为判断条件
        if(map.containsKey(user.getUserId())){
            return;
        }
        map.put(user.getUserId(), session);

    }

    //2.删除映射关系
    public void remove(User user, WebSocketSession session) {
        //这里要防止多开的情况
        if(map.get(user.getUserId())!=session){
            return;
        }
        map.remove(user.getUserId());
    }

    //查询映射关系
    public WebSocketSession get(Integer userId) {
        return map.get(userId);
    }

}
